<?php


namespace app\badmin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Mongo;
use think\Db;
use think\Exception;
use custom\Log;

class SystemLog extends BaseModel {

    static $setName = 'badmin_system_log';

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public static function getList($params) {
        $mongo = Mongo::getInstance();
        //删除大于90天的数据
//        $where = ['itime' => ['$lt' => time() - 7776000]];
//        $limit = ['limit' => 0];
//        $mongo->deldoc($where, $limit, self::$setName);
        $filter = [];
        //公司账号
        if ($params['account_type'] == 0) {
            $filter['company_id'] = ['$eq' => (int)$params['company_id']];
        } else {
            $filter['company_shop_id'] = ['$eq' => (int)$params['company_shop_id']];
        }
        if (!empty($params['admin_name'])) {
            $filter = ['admin_name' => ['$eq' => (string)trim($params['admin_name'])]];
        }
        $page = (int)$params['page'];
        $long = (int)$params['long'];
        $sort = ['_id' => -1];
        $cursor = $mongo->page($filter, $page, $long, self::$setName, $sort);
        $data = $cursor['data'];
        if (empty($data)) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
        } else {
            foreach ($data as $index => $item) {
                $data[$index]->itime = date('Y-m-d H:i:s', $item->itime);
                $data[$index]->url = "{$data[$index]->module}/{$data[$index]->controller}/{$data[$index]->action}";
            }
            $result = [
                'page'    => $cursor['page'],
                'pageNum' => $cursor['pageNum'],
                'count'   => $cursor['count'],
                'data'    => $data,
            ];
        }
        return $result;
    }

    /**
     * 保存操作日志
     * @param $data
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public static function saveSystemLog($data) {
        $mongo = Mongo::getInstance();
        $last = $mongo->select(self::$setName, [], ['limit' => 1, 'sort' => ['_id' => -1]]);
        if (empty($last)) {
            $data['_id'] = (int)1;
        } else {
            $last = (array)$last[0];
            $data['_id'] = (int)($last['_id'] + 1);
        }
        return $mongo->add($data, self::$setName);
    }


    /**
     * 操作记录
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function footPrint($uInfo) {
        try {
            $controller = strtolower(request()->controller());
            $action = strtolower(request()->action());
            $module = strtolower(request()->module());
            if ($controller != 'systemlog' || $controller != 'loginlog') {
                //菜单
                $core_menu = config('badmin_menu.' . $controller);
                if ($core_menu) {
                    $behavior = null;
                    foreach ($core_menu['children'] as $k1 => $v1) {
                        if ($v1['action'] == $action) {
                            $behavior = $v1['name'];
                        }
                    }
                    //公司账号
                    if ($uInfo['company_shop_id'] == 0) {
                        $tabeName = 'company';
                        $field = 'company_id';
                    } else {
                        $tabeName = 'company_shop';
                        $field = 'company_shop_id';
                    }
                    $admin_name = Db::name($tabeName)->getFieldByid($uInfo[$field], 'name');
                    if (isset($behavior)) {
                        $data = [
                            'company_shop_id' => (int)$uInfo['company_shop_id'],
                            'company_id'      => (int)$uInfo['company_id'],
                            'admin_id'        => (string)$uInfo['id'],
                            'admin_name'      => (string)$admin_name,
                            'menu_name'       => (string)$core_menu['name'],
                            'module'          => (string)$module,
                            'controller'      => (string)$controller,
                            'action'          => (string)$action,
                            'ip'              => (string)request()->ip(),
                            'itime'           => (string)time(),
                            'behavior'        => (string)$behavior,
                        ];
                        if (self::saveSystemLog($data) != true) throw  new Exception('操作日志写入失败', RespCode::PARAMS_ERR);
                    }
                }
            }
        } catch (Exception $e) {
            $err = "异常信息:{$e->getMessage()} | 异常所在的代码行:{$e->getLine()} | 异常文件{$e->getFile()} | php 版本 " . PHP_VERSION . "(" . PHP_OS . ")";
            Log::write($err, "footPrintErr.log");
        }
    }


}